<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/7/3
 */

namespace app\student\controller;


use app\classes\model\StudentLeaveModel;
use app\student\model\StudentAdjustModel;
use app\student\model\StudentModel;
use cmf\controller\UserBaseController;
use think\Db;

class FrontStudentController extends UserBaseController
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 家长孩子请假信息
     * @return mixed|\think\response\Redirect
     */
    public function index()
    {
        $limit = config('limit_front_per_page');
        $where = [];
        //当前家长
        $cur_uid = cmf_get_current_user_id();
        //获取家长的孩子
        $student_mdl = new StudentModel();
        $students = $student_mdl->getStudentsByPid($cur_uid, $this->front_shop_id);
        if (!$students) {
            $this->redirect('order/Order/add_student');
        }

        if (isset($_SESSION['student_id']) && !empty($_SESSION['student_id'])) {
            $student_id = $_SESSION['student_id'];
        } else {
            //设置当前学生
            $_SESSION['student_id'] = $students[0]['id'];
            //默认第一个孩子
            $student_id = $students[0]['id'];
        }

        //店铺ID
        $where['st.shop_id'] = ['=', $this->front_shop_id];
        $where['st.id'] = ['=', $student_id];

        //获取家长孩子请假信息
        $leave_model = new StudentLeaveModel();
        $data = $leave_model->getLeave($where, [], $limit, []);
        if (count($data) > 0) {
            //获取调课信息
            foreach ($data as $k => $v) {
                $adjust_where = [
                    'sa.leave_id' => $v['id'],
                    'sa.student_id' => $v['student_id'],
                    'sa.type' => 2,
                ];
                $adjust_mdl = new StudentAdjustModel();
                //获取学生请假调课信息
                $adjust_data = $adjust_mdl->getAdjustByField($adjust_where);
                if (count($adjust_data) > 0) {
                    $data[$k]['adjust_info'] = $adjust_data;
                }else{
                    $data[$k]['adjust_info'] = [];
                }
            }
        }

        $this->assign('student_id', $student_id);
        $this->assign('students', $students);
        $this->assign('leaves', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * 申请请假
     * @return mixed
     */
    public function add()
    {
        if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
            //跳转到家校通首页
            $this->redirect('jiaxiaotong/JiaXiaoTong/index');
        }
        $student_id = $_SESSION['student_id'];

        //当前家长
        $cur_uid = cmf_get_current_user_id();
        //获取家长的孩子
        $student_mdl = new StudentModel();
        $students = $student_mdl->getStudentsByPid($cur_uid, $this->front_shop_id);
        if (!$students) {
            return redirect('order/Order/add_student');
        }

        //获取学生所在的班级
        $classes = Db::name('class')->alias('cl')
            ->distinct(true)
            ->field('cl.id,cl.name')
            ->join('class_student cs', 'cs.class_id=cl.id')
            ->join('order o', 'o.class_id=cs.class_id and o.student_id=cs.student_id')
            ->where('cl.shop_id', 'eq', $this->front_shop_id)
            ->where('cl.delete_time', 'eq', 0)//未删除
            ->where('cl.class_status', 'neq', 2)//未结课
            ->where('cs.student_id', 'eq', $student_id)
            ->where('o.order_status', ['eq', 1], ['eq', 2], 'or')//订单已支付或已完成
            ->select();

        $this->assign('student_id', $student_id);
        $this->assign('students', $students);
        $this->assign('classes', $classes);
        return $this->fetch();
    }

    /**
     * 通过班级筛选排课课时
     * @return \think\response\Json
     */
    public function ajax_schedule()
    {
        $param = $this->request->post();

        if (empty($param['class_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '班级不能为空',
                'data' => []
            ];
            return json($json_data);
        }

        //获取班级
        $schedule = Db::name('course_schedule')->alias('cs')
            ->field('cs.*,FROM_UNIXTIME(cs.date, "%Y-%m-%d") as date_time')
            ->where('cs.class_id', 'eq', $param['class_id'])
            ->where('cs.date', 'gt', time())//当前时间以后的课时
            ->select();
        if (count($schedule) <= 0) {
            $json_data = [
                'code' => 0,
                'msg' => '没有更多数据',
                'class_id' => $param['class_id'],
                'data' => []
            ];
            return json($json_data);

        } else {
            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'class_id' => $param['class_id'],
                'data' => $schedule
            ];
            return json($json_data);
        }
    }

    /**
     *保存请假
     */
    public function addPost()
    {
        $cur_time = time();
        $validate = validate('FrontStudent');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            //验证
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            if(empty(trim($data['reason']))){
                $this->error('请假原因不能为空');
            }

            if (!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])) {
                //跳转到家校通首页
                $this->redirect('jiaxiaotong/JiaXiaoTong/index');
            }
            $student_id = $_SESSION['student_id'];

            //补课方式
            $change_course = $data['change_course'];
            if ($change_course != 0 && $change_course != 1 && $change_course != 2) {
                $this->error('请重新选择补课方式');
            }

            $class_id = $data['class_id'];
            $class = Db::name('class')->find($class_id);
            if (count($class) <= 0) {
                $this->error('没有该班级');
            }

            //进度
            $course_time = $data['course_time'];
            $schedule_num = $course_time;
            if (empty($schedule_num) || !is_numeric($schedule_num)) {
                $this->error('请求参数错误');
            }

            //请求补课次数控制
            if($change_course != 0){
                switch ($change_course){
                    case 1:
                        $type = 1;//申请录音
                        break;
                    case 2:
                        $type = 2;//申请调课
                        break;
                    default:
                        $type = 1;
                }

                $total = Db::name('student_adjust')
                    //->where('type', '=', $type)
                    ->where('student_id', '=', $data['student_id'])
                    ->where('old_school_id', '=', $class['school_id'])
                    ->where('old_class_id', '=', $class['id'])
                    ->count();
                if ($total >= 3) {
                    $this->error('补课方式最多可申请3次');
                }
            }

            //判断是否已请假
            $student_leave = Db::name('student_leave')
                ->where('student_id', 'eq', $student_id)
                ->where('class_id', 'eq', $class_id)
                ->where('schedule', 'eq', $schedule_num)
                ->find();
            if (count($student_leave) > 0) {
                $this->error('不可重复请假');
            }

            //获取该排课
            $course_schedule = Db::name('course_schedule')
                ->where('class_id', 'eq', $class_id)
                ->where('schedule', 'eq', $schedule_num)
                ->find();
            if (count($course_schedule) <= 0) {
                $this->error('没有该课时');
            }

            //请假数据
            $leave_data = [
                'student_id' => $student_id,
                'school_id' => $class['school_id'],
                'class_id' => $class['id'],
                'course_id' => $class['course_id'],
                'teacher_id' => $course_schedule['teacher_id'],
                'date' => $course_schedule['date'],
                'start_time' => $course_schedule['start_time'],
                'end_time' => $course_schedule['end_time'],
                'week' => $course_schedule['week'],
                'schedule' => $course_schedule['schedule'],
                'reason' => trim($data['reason']),
                'change_course' => $change_course,
                'status' => 0,
                'create_time' => $cur_time,
            ];

            $leave_mdl = new StudentLeaveModel();
            $id = $leave_mdl->allowField(true)->insertGetId($leave_data);
            if ($id) {
                $this->success('申请成功！', url('student/FrontStudent/index', ['student_id' => $student_id]));
            } else {
                $this->error('申请失败！');
            }
        } else {
            $this->error('请求错误');
        }
    }

    /**
     * 取消请假
     * @return \think\response\Json
     */
    public function cancel()
    {
        $param = $this->request->param();
        if(!isset($param['id']) || empty($param['id'])){
            $this->error('请求有误');
        }

        if(!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])){
            //跳转到家校通首页
            $this->error('没有选择学员','jiaxiaotong/JiaXiaoTong/index');
        }
        //当前学生
        $student_id = $_SESSION['student_id'];
        //请假id
        $leave_id = trim($param['id']);

        $where = [
            'leave_id' => ['=', $leave_id],
            'student_id' => ['=', $student_id],
        ];
        //检查调课
        $adjust = Db::name('student_adjust')->where($where)->find();
        if(count($adjust) > 0){
            $this->error('已调课不可取消请假');
        }

        //检查请假
        $leave_where = [
            'id' => ['=', $leave_id],
            'student_id' => ['=', $student_id],
        ];
        $leave = Db::name('student_leave')->where($leave_where)->find();
        if(count($leave) > 0) {
            //删除请假
            Db::name('student_leave')->where($leave_where)->delete();
            //记录日志
            $user = cmf_get_current_user();
            $student = Db::name('student')->find($student_id);
            $content = lang('FRONT_CANCEL_LEAVE',['name'=>$student['name'],'date'=>date('Y-m-d H:i')]);
            do_log($content,$leave_id,'student_leave',time(),$user['id']);

            $this->success('取消请假成功');
        }else{
            $this->error('没有该请假信息');
        }

    }

}